#pragma once
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <iostream>
#include <string>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <fcntl.h>
#define Creater  1
#define User     2
#define BaseSize 4096
#define Write    O_WRONLY
#define Read     O_RDONLY
#define Default -1
const std::string& Path = "makefifo";
class NamePipe
{
    private:
        bool OpenFifo(int mod){
            _fd = open(Path.c_str(), mod);
            if(_fd < 0)
                return false;
            return true;
        }
    public:
        NamePipe(const std::string &str, int who)
            : _path(str)
            , _id(who)
            , _fd(Default)
        {
            if(_id == Creater)
            {
                int ret = mkfifo(_path.c_str(), 0666);
                if (ret != 0)
                {
                    std::cerr << errno << " : " << strerror(errno) << std::endl;
                }
            }
        };
        bool OpenForRead(){
            return OpenFifo(Read);
        }
        bool OpenForWrite(){
            return OpenFifo(Write);
        }
        int WriteNamePipe(const std::string& str){
            int ret = write(_fd, str.c_str(), str.size());
            return -1;
        }
        int ReadNamePipe(std::string *buffer){
            char ret[BaseSize];
            int n = read(_fd, ret, sizeof(ret));
            if(n > 0)
            {
                ret[n] = 0;
                *buffer = ret;
            }
            return n;
        }
        ~NamePipe()
        {
            if(_id == Creater)
            {
                int ret = unlink(_path.c_str());
                if (ret != 0)
                {
                    std::cerr << errno << " : " << strerror(errno) << std::endl;
                }
            }
            if(_fd != Default)
                close(_fd);
        }

    private:
        std::string _path;
        int _id;
        int _fd;
};